import jwt
import datetime
from django.conf import settings


class JWTTool:
    def getToken(self, userid, account):
        # 生成token
        data = {
            "userid": userid,
            "account": account,
            "exp": datetime.datetime.now() + datetime.timedelta(hours=1)
        }
        return "Bearer " + jwt.encode(payload=data, key=settings.SECRET_KEY)

    def checkToken(self, token):
        try:
            return jwt.decode(token, key=settings.SECRET_KEY, algorithms=["HS256"])
        except jwt.ExpiredSignatureError:
            print("Token已过期")
            return None
        except jwt.InvalidTokenError:
            print("无效的Token")
            return None

tooljwt = JWTTool()